package com.mongo.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mongo.jdbc.core.JdbcMongodbCommand;

public abstract class MongodbAbstractStatement {

    protected boolean isClosed = false;
    protected Connection connection;
    protected ResultSet resultSet;
    protected String sql;
    
    private static Gson gson = new Gson();
    
    private JdbcMongodbCommand mongodbCommand = new JdbcMongodbCommand();
    
    public MongodbAbstractStatement() {
    	
    }
    protected MongodbAbstractStatement(String sql, Connection connection) {
        this.sql  = sql;
        this.connection = connection;
    }
    protected MongodbAbstractStatement(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(String sql) throws SQLException {

        if(isClosed)
            throw new SQLException("This statement is closed.");

        try {
    		Object result = mongodbCommand.command(connection.db, sql);
    
    		List<LinkedHashMap> data =new ArrayList<LinkedHashMap>();
    		data.add(gson.fromJson(result.toString(), LinkedHashMap.class));
            resultSet = new MongodbResultSet(data);
    		
            return true;

        } catch (Exception e) {
            throw new SQLException(e);
           
        }

    }
    
    public ResultSet executeQuery(String sql) throws SQLException {

        if(isClosed)
            throw new SQLException("This statement is closed.");

        try {
    		Object result = mongodbCommand.command(connection.db, sql);
    		System.out.println(result);
        	System.out.println("data111:"+result);

    		//Object[] values = new Object[] {result};

          //  resultSet = new MongodbResultSet(Arrays.copyOf(values, values.length, String[].class));
        	List<LinkedHashMap> data =gson.fromJson(result.toString(), new TypeToken<List<LinkedHashMap>>() {}.getType());
    		return  new MongodbResultSet(data);

        } catch (Exception e) {
            throw new SQLException(e);
           
        }

    }
    
    

}
